package test

import (
	"bytes"
	"encoding/binary"
	_ "github.com/golang/protobuf/proto"
	_ "github.com/hprose/hprose-golang/io"
	_ "github.com/trysh/ttb"
	_ "go-tcpFramework-rudy/protocol/pb"
	_ "io"
	"log"
	"net"
	_ "net/http/pprof"
	_ "runtime"
	"time"
)

type PackHeader struct {
	Identify [2]byte
	Length   int32
	Verify   byte
}

var rBuf []byte

func init() {
	rBuf = make([]byte, 1024)
}
func SendPackage(writer *net.TCPConn, payload []byte, length int) error {
	var header PackHeader
	header.Identify[0] = 0x40
	header.Identify[1] = 0x41
	header.Length = 4
	packbuf := bytes.Buffer{}

	buf := bytes.NewBuffer([]byte{})
	e := binary.Write(buf, binary.BigEndian, header.Length)
	if e != nil {
		log.Println(e.Error())
	}

	for _, v := range buf.Bytes() {
		header.Verify += v
	}
	err := binary.Write(&packbuf, binary.BigEndian, header.Identify)
	err = binary.Write(&packbuf, binary.BigEndian, header.Length)
	err = binary.Write(&packbuf, binary.BigEndian, header.Verify)
	if err != nil {
		log.Println(err.Error())
	}
	b := []byte{}

	//log.Println("Send length",wb)
	b = append(b, packbuf.Bytes()...)
	b = append(b, payload[0:length]...)
	log.Println(b)

	_, e = writer.Write(b)
	if e != nil {
		log.Println(e.Error())
		return e
	}

	return nil
}

func main() {
	for i := 0; i < 1; i++ {
		go func() {
			seq := int32(0)
			payload := bytes.NewBuffer([]byte{})
			server := "118.24.238.198:8052"
			servAddr, err := net.ResolveTCPAddr("tcp", server)
			if err != nil {
				log.Println(err.Error())
			}
			conn, err := net.DialTCP("tcp", nil, servAddr)
			if err != nil {
				log.Println(err.Error())
				return
			}
			for {
				seq++
				payload.Reset()
				binary.Write(payload, binary.BigEndian, seq)
				log.Println("start send", seq)
				e := SendPackage(conn, payload.Bytes(), payload.Len())
				//n ,e := conn.Write([]byte{'1','2','3','4'})

				if e != nil {
					log.Println("client exit")
					log.Println(e)
					return
				}
				time.Sleep(time.Second)
			}
			log.Println("client exit")
		}()
	}
	for {
		time.Sleep(time.Millisecond * 100)
	}
}
